import json
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from selenium.common.exceptions import NoSuchElementException
import random
import time


def get_news_info():
    # 设置 ChromeDriver 路径
    chrome_driver_path = "/usr/local/bin/chromedriver"

    print('START')

    # 配置 Chrome 选项
    options = Options()
    options.add_argument("--disable-blink-features=AutomationControlled")

    driver = webdriver.Chrome(service=Service(executable_path=chrome_driver_path), options=options)

    driver.get("http://www.ahsczx.com/Welcome/Main.aspx")

    wait = WebDriverWait(driver, 3)

    # 获取具有类名 `news_default_yw` 的元素
    elements_news_default_yw = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'cp')))

    # 获取具有类名 `news_yw_show` 的元素
    elements_news_yw_show = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'cp')))

    # 打印获取的元素内容
    # for element in elements_news_default_yw:
    #     print(f"Element with class 'news_default_yw': {element.text}")
    #
    # for element in elements_news_yw_show:
    #     print(f"Element with class 'news_yw_show': {element.text}")

    li_tags = driver.find_elements(By.XPATH, '//ul[@class="cp"]/li')
    for li in li_tags:
        a_tag = li.find_element(By.TAG_NAME, 'a')
        title = a_tag.get_attribute('title')
        href = a_tag.get_attribute('href')
        print(f'Title: {title}')
        print(f'Href: {href}')
        print('---')

        driver.execute_script("window.open('');")
        driver.switch_to.window(driver.window_handles[-1])

        # 访问超链接
        driver.get(href)

        # 等待页面加载完成
        wait = WebDriverWait(driver, 1)
        shownewstitle = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'shownewstitle'))).text
        shownewdate = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'shownewdate'))).text
        shownewscontent = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'shownewscontent'))).text

        print(f'shownewstitle: {shownewstitle}')
        print(f'shownewdate: {shownewdate}')
        print(f'Shownewscontent: {shownewscontent}')

        # 关闭当前标签页
        driver.close()
        driver.switch_to.window(driver.window_handles[0])

    time.sleep(20)
    driver.quit()

if __name__ == '__main__':
    get_news_info()
